package com.example.mouse;

import android.os.Handler;
import android.os.Looper;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketClient {
    private Socket socket;
    private PrintWriter writer;

    public void connect(String ip, int port, Runnable onSuccess, Runnable onError) {
        new Thread(() -> {
            try {
                socket = new Socket(ip, port);
                writer = new PrintWriter(socket.getOutputStream(), true);
                new Handler(Looper.getMainLooper()).post(onSuccess);
            } catch (IOException e) {
                new Handler(Looper.getMainLooper()).post(onError);
            }
        }).start();
    }

    public void sendMessage(String message) {
        if (writer != null) {
            new Thread(() -> writer.println(message)).start();
        }
    }
    public void disconnect() {
        try {
            if (socket != null) socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}